<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
      >
        <el-form-item
          label="产品序号"
          :label-width="formLabelWidth"
          prop="code"
        >
          <el-input v-model.trim="dataForm.code" placeholder="产品序号">
          </el-input>
        </el-form-item>
        <el-form-item
          label="产品类型"
          :label-width="formLabelWidth"
          prop="type"
        >
          <!-- <el-input v-model.trim="dataForm.type" placeholder="产品类型"> </el-input> -->
          <el-select
            v-model="dataForm.type"
            filterable
            placeholder="请选择产品类型"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="产品型号"
          :label-width="formLabelWidth"
          prop="model"
        >
          <el-input v-model.trim="dataForm.model" placeholder="产品型号">
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="合同编号" :label-width="formLabelWidth" prop="contractNumber">
          <el-input v-model.trim="dataForm.contractNumber" placeholder="合同编号"> </el-input>
        </el-form-item> -->
        <el-form-item
          label="额定容量"
          :label-width="formLabelWidth"
          prop="ratedCapacity"
        >
          <el-input v-model.trim="dataForm.ratedCapacity" placeholder="频率">
          </el-input>
        </el-form-item>
        <el-form-item
          label="额定电压比"
          :label-width="formLabelWidth"
          prop="ratedVoltageRatio"
        >
          <el-input
            v-model.trim="dataForm.ratedVoltageRatio"
            placeholder="额定电压"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="额定频率"
          :label-width="formLabelWidth"
          prop="ratedFrequency"
        >
          <el-input
            v-model.trim="dataForm.ratedFrequency"
            placeholder="额定频率"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="联结组标号"
          :label-width="formLabelWidth"
          prop="joinGroupLabel"
        >
          <el-input
            v-model.trim="dataForm.joinGroupLabel"
            placeholder="联结组标号"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="冷却方式"
          :label-width="formLabelWidth"
          prop="typeOfCooling"
        >
          <el-input
            v-model.trim="dataForm.typeOfCooling"
            placeholder="冷却方式"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="产品图纸"
          :label-width="formLabelWidth"
          prop="icon"
        >
          <el-upload
            class="upload-demo"
            :action="url + '/file/uploadFileInterface'"
            :headers="headers"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            :on-success="handleSuccess"
            :on-change="handleChange"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <!-- <el-upload :action="url + '/file/uploadFileInterface'" list-type="picture-card" :headers="headers" :file-list="fileList"
            :on-success="handleSuccess" :on-change="handleChange">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span class="el-upload-list__item-delete" @click="handleDownloadImg(file)">
                  <i class="el-icon-download"></i>
                </span>
                <span class="el-upload-list__item-delete" @click="handleRemoveImg(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload> -->
        </el-form-item>
        <el-form-item
          label="试验报告"
          :label-width="formLabelWidth"
          prop="icon"
        >
          <el-upload
            class="upload-demo"
            :action="url + '/file/uploadFileInterface'"
            :headers="headers"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove1"
            :file-list="fileList1"
            :on-success="handleSuccess1"
            :on-change="handleChange1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="排序号" :label-width="formLabelWidth" prop="orderNum">
				<el-input-number v-model="dataForm.orderNum" :min="0" controls-position="right" label="排序号">
				</el-input-number>
			</el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="dialogFormVisible = false"
            >取 消</el-button
          >
          <el-button
            size="small"
            type="primary"
            @click="dataFormSubmit()"
            :disabled="isDisabled"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleImg">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { v4 as uuidv4 } from "uuid";
import { getToken } from "@/utils/auth";
export default {
  emits: ["refreshDataList"],
  data() {
    return {
      dialogFormVisible: false,
      dialogVisibleImg: false,
      isDisabled: false,
      dialogImageUrl: "",
      dataForm: {
        id: 0,
        activateState: 0, //激活状态
        code: "", //产品序号
        driverId: "", //关联送货司机
        // frequency: '50Hz',//频率
        model: "", //型号
        projectId: "", //关联项目
        // ratedCurrent: '',//额定电流
        // ratedVoltage: '',//额定电压
        // standard: '',//执行标准
        type: "", //产品类型
        appendixName: "", //附件名称
        appendixUrl: "", //附件路径
        // contractNumber:'',//合同编号
        ratedCapacity: "", //额定容量
        ratedVoltageRatio: "", //额定电压比
        ratedFrequency: "", //额定频率
        joinGroupLabel: "", //联结组标号
        typeOfCooling: "", //冷却方式
      },
      projectList: [],
      driverList: [],
      fileList: [],
      fileList1: [],
      typeList: [
        {
          id: "电力变压器",
          name: "电力变压器",
        },
        {
          id: "换流变压器",
          name: "换流变压器",
        },
        {
          id: "整流变压器",
          name: "整流变压器",
        },
        {
          id: "电炉变压器",
          name: "电炉变压器",
        },
        {
          id: "试验变压器",
          name: "试验变压器",
        },
        {
          id: "电抗器",
          name: "电抗器",
        },
      ],
      url: process.env.VUE_APP_BASE_API,
      headers: {
        token: getToken(), //从cookie里获取token，并赋值  Authorization ，而不是token
      },
      dataRule: {
        code: [{ required: true, message: "产品序号不能为空" }],
        type: [{ required: true, message: "产品类型不能为空" }],
        model: [{ required: true, message: "型号不能为空" }],
        contractNumber: [{ required: true, message: "合同编号不能为空" }],
      },
      formLabelWidth: "140px",
    };
  },
  created() {},
  methods: {
    async init(id) {
      this.dataForm.id = id || 0;
      this.dialogFormVisible = true;
      this.$nextTick(async () => {
        this.$refs["dataForm"].resetFields();
        this.fileList = [];
        this.fileList1 = [];
        this.projectList = [];
        this.driverList = [];
        await this.Sevice({
          url: "/project/list",
          method: "get",
        }).then(async (res) => {
          if (res.code != 200) {
          } else {
            this.projectList = res.list;
          }
        });
        if (!this.dataForm.id) {
          // 新增
          // this.treeListTreeSetCurrentNode()
        } else {
          //获取详情
          this.Sevice({
            url: "/product/info/" + this.dataForm.id,
            method: "get",
          }).then(async (res) => {
            // console.log(res);
            if (res.code != 200) {
              // this.$message.error(res.data.msg)
            } else {
              this.dataForm.id = res.info.id;
              // this.dataForm.activateState = res.info.activateState?1:0;
              this.dataForm.code = res.info.code;
              this.dataForm.driverId = res.info.driverId;
              // this.dataForm.frequency = res.info.frequency;
              this.dataForm.model = res.info.model;
              this.dataForm.projectId = res.info.projectId;
              // this.dataForm.ratedCurrent = res.info.ratedCurrent;
              // this.dataForm.ratedVoltage = res.info.ratedVoltage;
              // this.dataForm.standard = res.info.standard;
              this.dataForm.type = res.info.type;
              this.dataForm.appendixUrl = res.info.appendixUrl;
              this.dataForm.appendixName = res.info.appendixName;
              this.dataForm.picUrl = res.info.picUrl;
              this.dataForm.picName = res.info.picName;

              this.dataForm.ratedCapacity = res.info.ratedCapacity;
              this.dataForm.ratedVoltageRatio = res.info.ratedVoltageRatio;
              this.dataForm.ratedFrequency = res.info.ratedFrequency;
              this.dataForm.joinGroupLabel = res.info.joinGroupLabel;
              this.dataForm.typeOfCooling = res.info.typeOfCooling;
              // this.dataForm.contractNumber=res.info.contractNumber;
              // this.getDriver(res.info.projectId)
              //附件
              if (this.dataForm.appendixUrl) {
                let appendixUrl = this.dataForm.appendixUrl.split(",");
                let appendixName = this.dataForm.appendixName.split(",");
                let list1 = [];
                for (let i = 0; i < appendixUrl.length; i++) {
                  list1.push({ url: appendixUrl[i], name: appendixName[i] });
                }
                this.fileList1 = list1;
              }
              //产品图纸
              if (this.dataForm.picName) {
                let picUrl = this.dataForm.picUrl.split(",");
                let picName = this.dataForm.picName.split(",");
                let list = [];
                for (let i = 0; i < picUrl.length; i++) {
                  // list.push({ url: picUrl[i], name: picName[i] })
                  list.push({
                    url: this.url + picUrl[i],
                    name: picName[i],
                    response: {
                      map: {
                        filePath: picUrl[i],
                        fileName: picName[i],
                      },
                    },
                  });
                }
                this.fileList = list;
              }
            }
          });
        }
      });
    },
    projectChange(id) {
      this.getDriver(id);
    },
    //获取司机
    getDriver(id) {
      this.Sevice({
        url: "/project/info/" + id,
        method: "get",
      }).then(async (res) => {
        // console.log(res);
        if (res.code != 200) {
          // this.$message.error(res.data.msg)
        } else {
          this.driverList = res.info.projectDrivers;
        }
      });
    },
    handlePreview(file) {
      this.fileDown(file);
    },
    beforeAvatarUpload(file) {
      console.log(file);
      let hz = file.name.split(".")[file.name.split(".").length - 1];
      // const isJPG = file.type === "image/jpg";

      //1MB=1024*1024(1MB=1024KB 1KB=1024MB)
      const is10M = file.size / 1024 / 1024 < 10;
      console.log(hz);
      //限制文件上传类型
      // if (hz!='obj') {
      // 	this.$message.error("只能上传obj格式的文件!");
      // 	return false
      // }

      return true;
    },
    handleRemoveImg(file) {
      console.log(file, this.fileList);
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid == file.uid) {
          this.fileList.splice(i, 1);
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },
    handleDownloadImg(file) {
      this.fileDown(file);
    },
    handleSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.fileList = fileList;
      } else {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid == file.uid) {
            fileList.splice(i, 1);
          }
        }
        this.$message({ message: response.msg, type: "error", duration: 1000 });
      }
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    //上传报告
    handleRemove1(file, fileList) {
      this.fileList1 = fileList;
    },
    handleSuccess1(response, file, fileList) {
      if (response.code == 200) {
        this.fileList1 = fileList;
      } else {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid == file.uid) {
            fileList.splice(i, 1);
          }
        }
        this.$message({ message: response.msg, type: "error", duration: 1000 });
      }
    },
    handleChange1(file, fileList) {
      this.fileList1 = fileList;
    },
    // 表单提交
    async dataFormSubmit() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          //附件
          let appendixUrl = [];
          let appendixName = [];
          console.log(this.fileList1);
          if (this.fileList1.length) {
            for (let i = 0; i < this.fileList1.length; i++) {
              if (this.fileList1[i].response) {
                appendixUrl.push(this.fileList1[i].response.map.filePath);
              } else {
                appendixUrl.push(this.fileList1[i].url);
              }
              appendixName.push(this.fileList1[i].name);
            }
          }
          this.dataForm.appendixUrl = appendixUrl.toString();
          this.dataForm.appendixName = appendixName.toString();
          //图纸
          let picUrl = [];
          let picName = [];
          console.log(this.fileList);
          if (this.fileList.length) {
            for (let i = 0; i < this.fileList.length; i++) {
              if (this.fileList[i].response) {
                picUrl.push(this.fileList[i].response.map.filePath);
              } else {
                picUrl.push(this.fileList[i].url);
              }
              picName.push(this.fileList[i].name);
            }
          }
          this.dataForm.picUrl = picUrl.toString();
          this.dataForm.picName = picName.toString();
          let url = this.dataForm.id ? "/product/update" : "/product/save";
          this.isDisabled = true;
          await this.Sevice({
            url: url,
            method: "post",
            data: {
              id: this.dataForm.id || undefined,
              // activateState: this.dataForm.activateState,
              appendixName: this.dataForm.appendixName,
              appendixUrl: this.dataForm.appendixUrl,
              picName: this.dataForm.picName,
              picUrl: this.dataForm.picUrl,
              code: this.dataForm.code,
              driverId: this.dataForm.driverId,
              // frequency: this.dataForm.frequency,
              model: this.dataForm.model,
              projectId: this.dataForm.projectId,

              // ratedCurrent: this.dataForm.ratedCurrent,
              // ratedVoltage: this.dataForm.ratedVoltage,
              // standard: this.dataForm.standard,
              projectId: this.dataForm.projectId,
              type: this.dataForm.type,
              // contractNumber:this.dataForm.contractNumber
              ratedCapacity: this.dataForm.ratedCapacity,
              ratedVoltageRatio: this.dataForm.ratedVoltageRatio,
              ratedFrequency: this.dataForm.ratedFrequency,
              joinGroupLabel: this.dataForm.joinGroupLabel,
              typeOfCooling: this.dataForm.typeOfCooling,
            },
          })
            .then((res) => {
              if (res && res.code == 200) {
                this.dialogFormVisible = false;
                this.$message({
                  message: res.msg,
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.isDisabled = false;
                    this.$emit("getUserlist");
                  },
                });
              } else {
                this.isDisabled = false;
              }
            })
            .catch((error) => {
              console.log(error);
              this.isDisabled = false;
            });
        }
      });
    },
  },
};
</script>

<style scoped>
.mod-menu .menu-list__input > .el-input__inner,
.mod-menu .icon-list__input > .el-input__inner {
  cursor: pointer;
}

.mod-menu__icon-popover {
  width: 458px;
  overflow: hidden;
}

.mod-menu__icon-inner {
  width: 478px;
  max-height: 258px;
  overflow-x: hidden;
  overflow-y: auto;
}

.mod-menu__icon-list {
  width: 458px;
  padding: 0;
  margin: -8px 0 0 -8px;
}

.mod-menu__icon-list > .el-button {
  padding: 8px;
  margin: 8px 0 0 8px;
}

.mod-menu__icon-list > .el-button > span {
  display: inline-block;
  vertical-align: middle;
  width: 18px;
  height: 18px;
  font-size: 18px;
}

.mod-menu .icon-list__tips {
  font-size: 18px;
  text-align: center;
  color: #e6a23c;
  cursor: pointer;
}

.el-tree {
  height: 200px;
  overflow-y: auto;
}
</style>
